const app = getApp(); // 获取应用实例
Page({
    /**
     * 页面的初始数据
     */
    data: {
      roundImages: [],
      roundNum:1,
      currentStage: 1,
      leaderIndex: 0,
      memNum: [3,4,4,5,5],
      roomCapacity: 9,
      players: [],
      leftPlayers: [],
      rightPlayers: [],
      blueTeamPlayers: [],
      redTeamPlayers: [],
      openid: '',
      userIndex: 0,
      userRole: {}, // 定义用户角色
      roleViewText: '', // 视角信息文本
      showRoleModal: false, // 控制身份展示modal的状态
      roles:[],//本地角色数组
      assassinPlayer: null,  // 刺客玩家的信息
      goodPlayers: [],  // 好人玩家列表
      slainModal: false,  // 控制“开始刺杀”modal的状态
      targetPlayer: null,  // 刺杀目标玩家
        
      roundResults: [],
      isPublished : false,
      hasVoted: false, // 当前用户是否已投票
      roomId:' '  ,
      midValue: 0,
      isslain:false

    },

    onLoad(options) {
        const roomId = options.roomId; // 从参数中获取 roomId
        this.setData({
            roomId:roomId
        })
    
        // 调用云函数获取openid
        wx.cloud.callFunction({
            name: 'get_openid',
            success: (res) => {
                const openid = res.result.openid;
                this.setData({ openid });
    
                // 先加载游戏数据，再加载房间数据
                this.loadGameData(roomId)
                    .then((gameData) => {
                        // 获取游戏中的 roles 数组，并存储到本地
                        const roles = gameData.roles;
                        this.setData({ roles }); // 保存 roles 到 data 中
                        // 添加日志打印
                        // console.log("游戏数据加载成功，角色列表:", roles);
                        // 加载房间数据
                        return this.loadRoomData(roomId)
                            .then(() => {
                                // 确保 memNum 和 roundNum 更新后调用 updateRoundImages
                                this.updateRoundImages();
                                // 使用 roles 调用 loadRoles
                                // console.log("加载完成，调用 loadRoles 函数，角色列表:", this.data.roles);
                                this.loadRoles(this.data.roles); // 使用本地的 roles 调用 loadRoles
                            });
                    })
                    .then(() => {
                        this.updateGameData(roomId);
                     })
                    .catch(error => {
                        console.error("加载数据失败：", error);
                    });
            },
            fail: (error) => {
                console.error("获取openid失败：", error);
                wx.showToast({
                    title: '获取用户信息失败',
                    icon: 'none'
                });
            }
        });
        this.getTeams(roomId);

        //定时更暂时关闭
       this.startUpdateGameData(roomId);

        // console.log(this.data.hasVoted);
        //this.executeTask();
        // console.table(this.data.players);
        // console.log(this.data.leaderIndex);
        // console.log('执行了Onload');
        // console.table(this.data.rightPlayers);
        // console.table(this.data.leftPlayers);
        // console.log(roomId);
    },

          //更新游戏数据
    updateGameData(roomId){
        console.log('调用upadte');
    const db = wx.cloud.database()
    // 异步获取数据
    db.collection('game')
    .where({ roomId: roomId })
    .get()
    .then(res => {
        // 检查 players 数组是否存在，并且 userIndex 是否有效
        const pl = res.data[0] && res.data[0].players; // 假设查询结果只有一个文档
        const cs = res.data[0].currentStage;
        const li = res.data[0].leaderIndex;
        const rr = res.data[0].roundResults;
        const rn = res.data[0].currentRound;
        const players = this.data.players;
        if (pl[this.data.userIndex].voted) {
            this.setData({
            hasVoted: true
            });
        }
        else{
            this.setData({
                hasVoted:false
            })
        }
        // console.table(pl);
        // console.log(this.data.roomCapacity);
        for(let i = 0; i < this.data.roomCapacity; i ++){
            if(pl[i].isTeamMember){
                players[i].isTeamMember = true;
            }
            if(pl[i].voted){
                players[i].voted = true;
            }
            players[i].isLeader = false;
        }

        players[li].isLeader = true;
        // console.table(players);
        this.setData({
            roundNum:rn,
            players:players,
            roundResults:rr,
            rightPlayers:this.getRightPlayers(),
            leftPlayers:this.getLeftPlayers(),
            currentStage:cs,
            leaderIndex:li
        });
        //发布队伍投票
        if(this.data.currentStage === 3){
            //console.log(1);
            this.checkAllVoted(); // 检查是否所有人都已投票
        }
        //执行任务投票
        if(this.data.currentStage === 4){
            this.checkAllVoted2();
        }

        if(rn > 3){

            let success=0,against=0; 
        //     for(let i=0;i<this.data.roundNum-1;i++) 
        //     { 
        //      console.log(i);
        //      if(rr[i].success) 
        //      { 
        //         success++; 
        //      } 
        //      else 
        //      { 
        //         against++; 
        //     } 
        //   } 
          success=3;
        //   cfonsole.log(success,against); 
          if(success>=3 && !this.data.isslain) 
          { 
            this.setData({
                currentStage:5,
                isslain:true
            });
            db.collection('game').where({ roomId: roomId }).update({
                data: {
                    currentStage: 5  // 设置为组队阶段
                }
            })
          } 
          if(against>=3) 
          { 
            this.setData({
                currentStage:6
            });
            db.collection('game').where({ roomId: roomId }).update({
                data: {
                    currentStage: 6  // 设置为组队阶段
                }
            })
               
          } 
        }
        // console.table(this.data.roundResults);
        // console.log(cs);
        // console.log(li);
        // console.table(this.data.players);
        // console.table(this.data.leftPlayers);
        // console.table(this.data.rightPlayers);
        // console.log(this.data.userIndex);
        // console.log(this.data.leaderIndex);
        // console.log(this.data.isPublished);
        // console.log(this.data.currentStage);

    })
    .catch(err => {
        console.error('查询游戏数据失败', err);
    });
    },


    loadRoles(roles) {
        if (!Array.isArray(roles) || roles.length === 0) {
            console.error("角色数据无效或为空");
            return;
        }
        
        const userIndex = this.data.userIndex; // 当前玩家的索引
        const userRoleNumber = roles[userIndex]; // 当前玩家的角色
    
        if (userRoleNumber === undefined) {
            console.error("未找到该玩家的角色信息");
            return;
        }
    
        let roleViewText = '';
    
        // 序号与角色名称映射
        const roleNames = {
            1: '梅林',
            2: '莫甘娜',
            3: '忠臣',
            4: '忠臣',
            5: '忠臣',
            6: '忠臣',
            7: '刺客',
            8: '莫德雷德',
            9: '奥伯伦',
            10: '爪牙',
            11: '派西维尔'
        };
    
        // 获取对应角色在 roles 数组中的玩家编号
        const getPlayerIndex = (roleNumber) => {
            return roles.indexOf(roleNumber) + 1; // 玩家编号从1开始
        };
    
        // 视角信息
        const visibleRoles = {
            1: [2, 7, 9, 10], // 梅林
            2: [7, 10, 8],    // 莫甘娜
            7: [2, 10, 8],    // 刺客
            10: [7, 2, 8],    // 爪牙
            8: [7, 2, 10],    // 莫德雷德
            9: [],            // 奥伯伦
            11: [1, 2]        // 派西维尔
        };
    
        const visibleIndexes = visibleRoles[userRoleNumber] || [];
        const visiblePlayers = visibleIndexes.filter(role => roles.includes(role)).map(role => getPlayerIndex(role));
    
        // 按玩家序号从小到大排序
        const sortedVisiblePlayers = visiblePlayers.sort((a, b) => a - b);
    
        if (userRoleNumber === 1) { // 梅林的视角
            roleViewText = `你可以看到: ${sortedVisiblePlayers.join(', ')}号玩家`;
        } else if (userRoleNumber === 11) { // 派西维尔的视角
            const merlinIndex = getPlayerIndex(1);
            const morganaIndex = getPlayerIndex(2);
            const sortedPlayers = [merlinIndex, morganaIndex].sort((a, b) => a - b);
            roleViewText = `梅林和莫甘娜存在于 ${sortedPlayers[0]} 号与 ${sortedPlayers[1]} 号玩家中`;
        } else if (sortedVisiblePlayers.length > 0) {
            roleViewText = `你可以看到: ${sortedVisiblePlayers.join(', ')}号玩家`;
        } else {
            roleViewText = "你没有视角";
        }
    
        

        const imagePath = `cloud://avalon-cloud-1gg01hi5d0e8cec0.6176-avalon-cloud-1gg01hi5d0e8cec0-1330536532/images/role/${userRoleNumber}.png`;
    
        this.setData({
            userRole: { number: userRoleNumber, name: roleNames[userRoleNumber], image: imagePath },
            roleViewText,
            showRoleModal: true ,// 显示角色信息
           
        });
    
        console.log(`玩家${userIndex + 1}的角色是: ${roleNames[userRoleNumber]}`);
        console.log(`视角信息: ${roleViewText}`);
    },
    
    confirmRole() {
        this.setData({
            showRoleModal: false // 关闭身份modal
        });
    },
    checkRole() {
      this.setData({
          showRoleModal: true // 显示身份modal
      });
    },

    onHide() {
        this.stopGameDataUpdate();
      },
    
      /**
       * 生命周期函数--监听页面卸载
       */
      onUnload() {
        
        this.stopGameDataUpdate();
      },

// 从 rooms 集合中加载房间数据
loadRoomData(roomId) {
    const db = wx.cloud.database();
    return db.collection('rooms').where({ roomId: roomId }).get()
        .then(res => {
            if (res.data.length > 0) {
                const roomData = res.data[0];
                const { selectedCapacity, userList } = roomData;

                // 检查 userList 是否有效
                if (!userList || !Array.isArray(userList)) {
                    console.error("无效的玩家列表: ", userList);
                    return;
                }

                // 使用本地的 leaderIndex
                const { leaderIndex } = this.data;

                // 根据 selectedCapacity 初始化 memNum
                let memNum;
                switch (selectedCapacity) {
                    case 5:
                        memNum = [2, 3, 2, 3, 3];
                        break;
                    case 6:
                        memNum = [2, 3, 4, 3, 4];
                        break;
                    case 7:
                        memNum = [2, 3, 3, 4, 4];
                        break;
                    case 8:
                    case 9:
                    case 10:
                        memNum = [3, 4, 4, 5, 5];
                        break;
                    default:
                        console.error("无效的房间容量:", selectedCapacity);
                        return;
                }

                // 获取当前玩家的索引
                const userIndex = userList.findIndex(user => user.openid === this.data.openid);
                //console.log("当前玩家的索引为:", userIndex);

                // 初始化玩家列表
                const players = userList.map((user, index) => ({
                    avatar: user.avatarUrl,
                    nickname: `${index + 1}号 ${user.nickname}`,
                    isLeader: index === leaderIndex,
                    isTeamMember: false,
                    voted:false
                }));

                // 设置左侧和右侧玩家列表A
                const mid = Math.ceil(selectedCapacity / 2);

                this.setData({
                    players,
                    roomCapacity:selectedCapacity,
                    memNum,
                    userIndex,
                    leftPlayers: players.slice(0, mid),
                    rightPlayers: players.slice(mid),
                    // blueTeamPlayers: blueTeamPlayers,
                    // redTeamPlayers: redTeamPlayers
                    midValue:mid
                });

                

                const assassinIndex = this.data.roles.findIndex(role => role === 7);  // 假设刺客的角色编号是 7
                //console.log("刺客的索引:", assassinIndex);

                let assassinPlayer = null;

                if (assassinIndex !== -1) {
                    // 找到刺客玩家的信息
                    assassinPlayer = players[assassinIndex];
                    console.log("刺客玩家:", assassinPlayer);
                }
                this.setData({
                    assassinPlayer: assassinPlayer  // 单独存储刺客玩家的信息，方便在页面中显示
                });

            }
        })
        .catch(error => {
            console.error("加载房间数据失败：", error);
        });
},


// 从 game 集合中加载游戏数据并返回角色信息
loadGameData(roomId) {
    const db = wx.cloud.database();
    return db.collection('game').where({ roomId:this.data.roomId }).get()
        .then(res => {
            if (res.data.length > 0) {
                const gameData = res.data[0];
                
                // 打印日志，确认从数据库获取的 gameData
               // console.log("从数据库获取的游戏数据:", gameData);

                // 设置 leaderIndex 和 roundNum，返回游戏数据
                this.setData({
                    leaderIndex: gameData.leaderIndex,
                    roundNum: gameData.currentRound,
                    currentStage: gameData.currentStage,
                    // currentStage:6
                });

                return gameData; // 返回完整的 gameData 包含 roles
            } else {
                throw new Error('未找到对应的游戏数据');
            }
        })
        .catch(error => {
            console.error("加载游戏数据失败：", error);
            throw error;
        });
},

onShow() {
    const roomId = this.data.roomId; // 获取房间 ID
    this.loadGameData(roomId)
        .then(() => {
        this.updateRoundImages();
        })
        .catch(error => {
        console.error("加载游戏数据失败：", error);
        });
},
  


    updateRoundImages() {
        const { roundNum, memNum } = this.data;
        const Images = [];
    //    console.table(this.data.roundResults);
        for (let index = 0; index < 5; index++) {
          let imagePath = '';
          // 当前轮显示为蓝色数字
          if (index + 1 === roundNum) {
            imagePath = `cloud://avalon-cloud-1gg01hi5d0e8cec0.6176-avalon-cloud-1gg01hi5d0e8cec0-1330536532/images/main/${memNum[index]}.png`; // 确保路径正确
          }
          // 过往轮显示为失败图片
         
          else if (index + 1 < roundNum) {
            // console.log(this.data.roundResults[index].success);
            // console.log(index);
            imagePath = `cloud://avalon-cloud-1gg01hi5d0e8cec0.6176-avalon-cloud-1gg01hi5d0e8cec0-1330536532/images/main/success.png`; 
            //else imagePath = `cloud://avalon-cloud-1gg01hi5d0e8cec0.6176-avalon-cloud-1gg01hi5d0e8cec0-1330536532/images/main/fail.png`; // 替换为实际结果的图片 
          }
          // 未到达轮显示为灰色数字
          else {
            imagePath = `cloud://avalon-cloud-1gg01hi5d0e8cec0.6176-avalon-cloud-1gg01hi5d0e8cec0-1330536532/images/main/${memNum[index]}-grey.png`; // 确保路径正确
          }
          Images.push(imagePath);
        }
        this.setData({
          roundImages: Images // 直接设置 Images 数组为图片路径
        });
      },
      

  
    onImgTap(event) {
      const index = event.currentTarget.dataset.index;
      const roundNum = this.data.roundNum;
      const memNum = this.data.memNum;
        
      //当前轮和未到达的轮，点击提示人数
      if (index + 1 >= roundNum) {
        if (this.data.players.length > 7 && index === 3) {
          wx.showModal({
            title: '提示',
            content: `该轮需要${memNum[index]}个队员，且为保护轮，1人投失败判定成功，需要2人以上投失败才判定失败`,
            showCancel: false
          });
        } else {
          wx.showModal({
            title: '提示',
            content: `该轮需要${memNum[index]}个队员`,
            showCancel: false
          });
        }
      } 
      //已完成的轮，跳转至结果页（也可使用Modal）
      else {
        const support = this.data.roundResults[index].resCount.support;
        const against = this.data.roundResults[index].resCount.against;
        wx.showModal({
            title: '提示',
            content: `该轮${support}人支持，${against}人反对`,
            showCancel: false
        });
      }
    },
  
    navigateToRules() {
      wx.navigateTo({
        url: '/pages/rules/rules'
      });
    },
  
    exitRoom() {
      wx.showModal({
        title: '提示',
        content: '确定离开房间？',
        confirmText: '确定',
        cancelText: '取消',
        confirmColor: '#FF4D4D',
        cancelColor: '#999999',
        success(res) {
          if (res.confirm) {
            wx.navigateBack();
          }
        }
      });
    },

    // 开始刺杀按钮点击事件
        slain() {
        // 隐藏刺杀按钮
        this.setData({
            assassinPlayer: null,  // 刺客玩家信息清空
            slainModal: true,  // 显示提示框
        });

        // 提示：你即将选择一个角色进行刺杀
        wx.showModal({
            title: '刺杀提醒',
            content: '你即将选择一名角色进行刺杀。注意，刺杀失败会导致游戏失败！',
            showCancel: false,
            success: (res) => {
            if (res.confirm) {
                // 获取可以被刺杀的好人玩家（非刺客和恶人角色）
                const goodPlayers = this.data.players.filter(player => {
                return player.role !== 11 && player.role !== 13 && player.role !== 9 && player.role !== 8;  // 刺客、莫甘娜、奥伯伦、莫德雷德不能成为目标
                });

                this.setData({
                goodPlayers: goodPlayers,  // 设置好人玩家s列表
                
                });
            }
            }
        });
        },

        // 选择刺杀目标
        selectTarget(player) {
        
        const targetPlayer = player;  // 获取目标玩家信息

        

        // 存储目标玩家信息
        this.setData({
            targetPlayer: targetPlayer,  // 保存目标玩家信息
        });

         // 确保当前玩家是刺客 
        const userRoleNumber = this.data.userRole.number; // 当前玩家的角色编号 
        if (userRoleNumber !== 7) { 
            // 如果当前玩家不是刺客，弹出提示 
            wx.showToast({ 
            title: '你不是刺客，无法选择目标！', 
            icon: 'none', 
            }); 
            return; 
        }

        // 弹出确认框，确认是否刺杀
        wx.showModal({
            title: '确认刺杀',
            content: `是否刺杀 ${targetPlayer.nickname}？`,
            success: (res) => {
            if (res.confirm) {
                this.confirmSlain(targetPlayer);
            } else {
                // 取消刺杀，重新选择目标
                this.setData({
                targetPlayer: null,  // 清空当前选择的目标
                });
            }
            }
        });

        // 更新UI显示目标玩家
        // 你可以在页面上添加相关的UI来显示选中的目标
        console.log(`刺客选择的目标是: ${targetPlayer.nickname}`);
        },

        // 确认刺杀
        confirmSlain(targetPlayer) {
        // 提取昵称的第一位数字作为索引
        const index = parseInt(targetPlayer.nickname.match(/^\d+/)[0], 10);

        const userRoleNumber = this.data.roles[index-1]; // 当前玩家的角色编号
        console.log(`确认后是: ${userRoleNumber}`);
        if (userRoleNumber === 1) {  // 如果目标角色是梅林
            wx.showModal({
            title: '刺杀成功',
            content: '刺杀梅林成功！',
            showCancel: false,
            success: (res) => {
                if (res.confirm) {
                // 刺杀成功后，设置游戏进入第六阶段
                this.setData({
                currentStage: 6,  // 设置为第六阶段
                gameResult: '胜利',  // 游戏胜利
                });
                const db = wx.cloud.database();
                db.collection('game').where({ roomId: this.data.roomId }).update({
                    data: {
                        currentStage: 6  // 设置为组队阶段
                    }
                })
                }
            }
            });
        } else {  // 如果目标不是梅林
            wx.showModal({
            title: '刺杀失败',
            content: '刺杀失败！目标不是梅林。',
            showCancel: false,
            success: (res) => {
                if (res.confirm) {
                // 刺杀失败后，设置游戏进入第六阶段
                this.setData({
                currentStage: 6,  // 设置为第六阶段
                gameResult: '失败',  // 游戏失败
                });
                const db = wx.cloud.database();
                db.collection('game').where({ roomId: this.data.roomId }).update({
                    data: {
                        currentStage: 6  // 设置为组队阶段
                    }
                })
                }
            }
            });
        }
        },

        getTeams(roomId) {
            const db = wx.cloud.database();
            const roomsCollection = db.collection('rooms');
            const gameCollection = db.collection('game');

            // 加载房间数据
            return roomsCollection.where({ roomId }).get()
                .then(roomRes => {
                    if (roomRes.data.length === 0) {
                        console.error("找不到该房间数据");
                        return;
                    }

                    const roomData = roomRes.data[0];
                    const { userList } = roomData;

                    // 加载游戏数据
                    return gameCollection.where({ roomId }).get().then(gameRes => {
                        if (gameRes.data.length === 0) {
                            console.error("找不到该游戏数据");
                            return;
                        }

                        const gameData = gameRes.data[0];
                        const { roles } = gameData;  // 角色数据

                        // 蓝方和红方角色编号
                        const blueTeamRoles = [1, 3, 4, 5, 6, 11];
                        const redTeamRoles = [2, 7, 8, 9, 10];

                        // 初始化蓝方和红方玩家列表
                        const blueTeamPlayers = [];
                        const redTeamPlayers = [];

                        // 遍历 userList 根据角色编号将玩家分配到蓝方或红方
                        userList.forEach((user, index) => {
                            const player = {
                                avatar: user.avatarUrl,
                                nickname: `${index + 1}号 ${user.nickname}`,
                            };

                            // 判断该角色是否属于蓝方
                            if (blueTeamRoles.includes(roles[index])) {
                                blueTeamPlayers.push(player);
                            }
                            // 判断该角色是否属于红方
                            else if (redTeamRoles.includes(roles[index])) {
                                redTeamPlayers.push(player);
                            }
                        });

                        console.log("蓝方玩家:", blueTeamPlayers);
                        console.log("红方玩家:", redTeamPlayers);

                        this.setData( {
                            blueTeamPlayers: blueTeamPlayers,
                            redTeamPlayers: redTeamPlayers
                        });
                    });
                })
                .catch(error => {
                    console.error("获取房间数据或游戏数据失败：", error);
                });
        },

      //定时更新游戏数据
      startUpdateGameData(roomId){
        // 保存定时器的ID，以便之后可以清除它  
        this.gameDataUpdateInterval = setInterval(() => {  
            this.updateGameData(roomId);
            this.updateRoundImages();
        }, 5000); // 6000毫秒 
      },

      stopGameDataUpdate: function() {  
        // 清除定时器  
        clearInterval(this.gameDataUpdateInterval);  
      }, 

      // 进入组队阶段的方法
        enterTeamStage() {
            const db = wx.cloud.database();
            const roomId = this.data.roomId;
        
            db.collection('game').where({ roomId: roomId }).update({
                data: {
                    currentStage: 2  // 设置为组队阶段
                }
            }).then(() => {
                console.log("成功进入组队阶段");
                this.setData({
                    currentStage: 2
                });
            }).catch(error => {
                console.error("进入组队阶段失败：", error);
            });
            },
    
        //选人按钮
        selectPlayer(index) {
            // console.log('选人');
            // const index = e.currentTarget.dataset.index; // 获取点击的索引
            const isLeader = this.data.userIndex === this.data.leaderIndex; // 判断当前用户是否为车长
            const currentStage = this.data.currentStage; // 获取当前阶段
            const maxMembers = this.data.memNum[this.data.roundNum - 1]; // 当前轮需要的队员数
          
            // 如果不是车长或不在组队阶段，直接返回
            if (!isLeader || currentStage !== 2) return;
            // console.log(index);
          
            // 获取对应的玩家对象
            const player = this.data.players[index]; // 直接使用传入的 index
    
            // 确保 player 存在
            if (!player) {
                console.error("未找到对应的玩家:", index);
                return;
            }
          
            // 切换 isTeamMember 状态
            player.isTeamMember = !player.isTeamMember;
          
            // 更新已选择的队员数量
            const selectedCount = this.data.players.filter(p => p.isTeamMember).length; // 统计 isTeamMember 为 true 的人数
    
            // console.log(isLeader);
            // console.log(this.data.isPublished);
          
            // 如果已选择的队员数量超过最大人数，提示并恢复状态
            if (selectedCount > maxMembers) {
              wx.showToast({
                title: `最多只能选择 ${maxMembers} 名队员`,
                icon: 'none'
              });
              player.isTeamMember = false; // 恢复状态
              return;
            }
    
            //如果人数达到要求则可以点击发布按钮
            if(selectedCount === maxMembers){
                this.setData({
                    isPublished: true
                });
            }
            else{
                this.setData({
                    isPublished: false
                });
            }
          
            // 更新数据
            this.setData({
              players: this.data.players,
              leftPlayers: this.getLeftPlayers(),
              rightPlayers: this.getRightPlayers()
            });
          
          },
    
        //发布队伍
        publishTeam() {

            this.setData({
                isPublished:false
            })
            const { players } = this.data;
          
            // 获取已选择的队员
            // const teamMembers = players.filter(p => p.isTeamMember);
          
            //所选队员足够才会有发布按钮，，不需要这个
            // if (teamMembers.length < this.data.memNum[this.data.roundNum - 1]) {
            //   wx.showToast({
            //     title: '请确保选择足够的队员',
            //     icon: 'none'
            //   });
            //   return;
            // }
          
            // 更新数据库逻辑
            this.updateTeamInDB();
          },
          
    
        // 更新数据库中的队员信息
        updateTeamInDB() {
            const db = wx.cloud.database();
            const roomId = this.data.roomId;
        
            db.collection('game').where({ roomId: roomId }).update({
            data: {
                players: this.data.players, // 更新 players 数组
                currentStage:3,
                voteSupport: 0,
                voteAgainst: 0,
            }
            }).then(() => {
            wx.showToast({
                title: '队伍发布成功',
                icon: 'success'
                });
            console.log("发布队伍成功");
            // // 清空选择状态
            // this.setData({
            //     players: this.data.players.map(p => ({ ...p, isTeamMember: false })),
            //     selectedCount: 0,
            //     });
            // 进入投票阶段
            // this.setData({
            //     currentStage: 3,
            //     players: this.data.players.map(p => ({ ...p, voted: false })), // 重置投票状态
            // });
            }).catch(error => {
            wx.showToast({
                title: '发布失败，请重试',
                icon: 'none'
                });
            console.error("发布队伍失败：", error);
            });
        },
    
          getLeftPlayers() {
            return this.data.players.slice(0, Math.ceil(this.data.roomCapacity / 2));
          },
          
          getRightPlayers() {
            return this.data.players.slice(Math.ceil(this.data.roomCapacity / 2), this.data.roomCapacity);
          },
    
    
          voteSupport() {
            if(this.data.hasVoted){
                return;
            }
            // console.log(this.data.hasVoted);
            // this.data.hasVoted = true;
            const db = wx.cloud.database();
            const roomId = this.data.roomId;
            
            const player = this.data.players[this.data.userIndex]; 
          
            player.voted = true;
            db.collection('game').where({ roomId: roomId }).update({
            data: {
                players: this.data.players, // 更新 players 数组
                currentStage:3,
                voteSupport: db.command.inc(1)
            }
            }).then(() => {
            wx.showToast({
                title: '投票成功',
                icon: 'success'
                });
            console.log("投票成功");
            // this.checkAllVoted(); // 检查是否所有人都已投票
        }).catch(error => {
            wx.showToast({
                title: '投票失败，请重试',
                icon: 'none'
                });
            console.error("投票失败：", error);
            });
        },
          
          voteAgainst() {
            if(this.data.hasVoted){
                return;
            }
            const db = wx.cloud.database();
            const roomId = this.data.roomId;
            
            const player = this.data.players[this.data.userIndex]; 
          
            player.voted = true;
            db.collection('game').where({ roomId: roomId }).update({
            data: {
                players: this.data.players, // 更新 players 数组
                currentStage:3,
                voteAgainst: db.command.inc(1)
            }
            }).then(() => {
            wx.showToast({
                title: '投票成功',
                icon: 'success'
                });
            console.log("投票成功");
            // this.checkAllVoted(); // 检查是否所有人都已投票
        }).catch(error => {
            wx.showToast({
                title: '投票失败，请重试',
                icon: 'none'
                });
            console.error("投票失败：", error);
            });
          },
          
    
          
          async checkAllVoted() {  
            if(this.data.currentStage !== 3){
                return
            }
            const db = wx.cloud.database();  
            const roomId = this.data.roomId;  
            const totalPlayers = this.data.players.length;  
            
            try {  
              const result = await db.collection('game').where({ roomId: roomId }).get();  
              if (result.data.length > 0) {  
                const gameData = result.data[0]; // 假设每个房间只有一条记录  
                const voteSupport = gameData.voteSupport || 0; // 使用 || 0 来处理可能的 undefined 情况  
                const voteAgainst = gameData.voteAgainst || 0;  
            
                if (voteSupport + voteAgainst >= totalPlayers) {  
                  await this.showVoteResults(voteSupport, voteAgainst);  
                }  
              } else {  
                console.error('未找到对应的房间数据');  
              }  
            } catch (error) {  
              console.error('获取云数据库数据时出错:', error);  
            }  
          },
          
          async showVoteResults(voteSupport, voteAgainst) {  
            try {  
              if (voteSupport >= voteAgainst) {  
                wx.showToast({  
                  title: '任务执行',  
                  icon: 'success' ,
                  duration: 3000  // 5秒 
                });  
                // 执行任务逻辑  
                await this.executeTask();  
              } else {  
                wx.showToast({  
                  title: '切换车长',  
                  icon: 'none'  
                });  
                // 切换车长并重置相关变量  
                await this.switchLeader();  
              }  
            } catch (error) {  
              console.error('在执行投票结果时出错:', error);  
            }  
          },
          
          switchLeader() {
            const pls = this.data.players;
            let li = this.data.leaderIndex;
            li = (li + 1) % 5;
            for(let i = 0; i < this.data.roomCapacity; i ++){
                pls[i].isTeamMember = false;
                pls[i].voted = false;
                pls[i].isLeader = (i === li );
            }
            const db = wx.cloud.database();
            const roomId = this.data.roomId;
        
            db.collection('game').where({ roomId: roomId }).update({
            data: {
                players: pls, // 更新 players 数组
                currentStage:1,
                voteSupport: 0,
                voteAgainst: 0,
                leaderIndex: li
            }
            }).then(() => {
            wx.showToast({
                title: '组队失败！',
                icon: 'success'
                });
            console.log("组队失败");
            });
            
          },
    
          executeTask() {
            const { players, roundNum, roomId, roomCapacity } = this.data;
          
            // 清除每人的投票状态
           for(let i = 0; i < roomCapacity; i ++){
               players[i].voted = false;
           }
          
            this.setData({
              currentStage: 4, // 更新为执行任务阶段
              players: players,
            });
    
            const db = wx.cloud.database();
        
            db.collection('game').where({roomId: roomId}).update({
                data: {
                  players:players,
                  currentStage:4,
                  voteAgainst:0,
                  voteSupport:0
                },
              });
    
            
          
          },
    
          voteSupport2() {
            if(this.data.hasVoted){
                return;
            }
            // console.log(this.data.hasVoted);
            // this.data.hasVoted = true;
            const db = wx.cloud.database();
            const roomId = this.data.roomId;
            
            const player = this.data.players[this.data.userIndex]; 
          
            player.voted = true;
            db.collection('game').where({ roomId: roomId }).update({
            data: {
                players: this.data.players, // 更新 players 数组
                voteSupport: db.command.inc(1)
            }
            }).then(() => {
            wx.showToast({
                title: '投票成功',
                icon: 'success'
                });
            console.log("投票成功");
            // this.checkAllVoted(); // 检查是否所有人都已投票
        }).catch(error => {
            wx.showToast({
                title: '投票失败，请重试',
                icon: 'none'
                });
            console.error("投票失败：", error);
            });
        },
    
        voteAgainst2() {
            if(this.data.hasVoted){
                return;
            }
            const db = wx.cloud.database();
            const roomId = this.data.roomId;
            
            const player = this.data.players[this.data.userIndex]; 
          
            player.voted = true;
            db.collection('game').where({ roomId: roomId }).update({
            data: {
                players: this.data.players, // 更新 players 数组
                voteAgainst: db.command.inc(1)
            }
            }).then(() => {
            wx.showToast({
                title: '投票成功',
                icon: 'success'
                });
            console.log("投票成功");
            // this.checkAllVoted(); // 检查是否所有人都已投票
        }).catch(error => {
            wx.showToast({
                title: '投票失败，请重试',
                icon: 'none'
                });
            console.error("投票失败：", error);
            });
          },
    
          async checkAllVoted2() {  
            if(this.data.currentStage !== 4){
                return
            }
            const db = wx.cloud.database();  
            const roomId = this.data.roomId;  
            // const totalPlayers = this.data.players.length;  
            
            try {  
              const result = await db.collection('game').where({ roomId: roomId }).get();  
              if (result.data.length > 0) {  
                const gameData = result.data[0]; // 假设每个房间只有一条记录  
                const voteSupport = gameData.voteSupport || 0; // 使用 || 0 来处理可能的 undefined 情况  
                const voteAgainst = gameData.voteAgainst || 0;  
    
                const length = this.data.memNum[this.data.roundNum-1];
                // console.log(length);
    
            
                if (voteSupport + voteAgainst >= length) {  
                  await this.showVoteResults2(voteSupport, voteAgainst);  
                }  
              } else {  
                console.error('未找到对应的房间数据');  
              }  
            } catch (error) {  
              console.error('获取云数据库数据时出错:', error);  
            }  
          },
    
          async showVoteResults2(voteSupport, voteAgainst) {  
            try {  
              if (voteAgainst !== 0) {  
                wx.showToast({  
                  title: '任务失败',  
                  icon:'fail',
                  duration: 3000  // 5秒 
                });  
              } else {  
                wx.showToast({  
                  title: '任务成功',  
                  icon: 'success' ,
                });  
              }  
             //更新游戏数据
             this.updateVoteResult(voteSupport, voteAgainst);
             //进入下一轮
             this.resetGameState();
            } catch (error) {  
              console.error('在执行投票结果时出错:', error);  
            }  
          },
    
          updateVoteResult(voteSupport, voteAgainst){
              //console.log(1);
              const{roomId, roundNum} = this.data;
              let result = true;
              if(voteAgainst !== 0){
                  result = false;
              }
    
            // 构建投票结果对象
            const roundResult = {
                resCount: {
                support: voteSupport,
                against: voteAgainst
                },
                round: this.data.roundNum,
                success:result
            };
    
            const db = wx.cloud.database();
        
            db.collection('game').where({ roomId: roomId }).update({
            data: {
                [`roundResults.${roundNum - 1}`]: roundResult
            }
            })
          },
    
          resetGameState() {
            // 重置游戏状态
            this.setData({
              currentStage: 1, // 回到组队阶段
              roundNum: this.data.roundNum + 1, // 增加回合数
              leaderIndex:(this.data.leaderIndex + 1)%5,
              players: this.data.players.map(player => ({
                ...player,
                voted: false, // 重置投票状态
                isTeamMember: false // 重置队员状态
              }))
            });
          
            // 更新数据库中的玩家状态
            this.updatePlayersInDB();
          },
    
          updatePlayersInDB() {
            const { roomId, players, currentStage, roundNum, leaderIndex } = this.data;
          
            wx.cloud.database().collection('game').where({roomId: roomId}).update({
              data: {
                currentStage:currentStage,
                currentRound:roundNum,
                leaderIndex:leaderIndex,
                players: players
              },
            });
        },

        select(e){
            const currentStage = this.data.currentStage;
            if(currentStage === 2){
                this.selectPlayer(e.currentTarget.dataset.index);
            }
            else if(currentStage === 5){
                this.selectTarget(e.currentTarget.dataset.player);
            }
        },

 
  //从数据库同步单轮结果 
  //重置每人isMember 
  //待插入 
  entering_nextround() 
  { 
    wx.cloud.callFunction({ 
      name: 'next_round', // 云函数名称 
      data: {   
        roomId: this.data.roomId   
      },   
      success: (res) => { 
        console.log(res.result.message); 
      }, 
      fail: (error) => { 
        console.log('entering_nextround error!') 
      } 
    }); 
  }, 
 
  //记录单轮结果 
  //待插入 
  record_round_result(current_round) 
  { 
    const db = wx.cloud.database(); 
    return db.collection('game').where({ roomId: this.data.roomId }).get() 
      .then(res => { 
        if (res.data.length > 0) { 
          const gameData = res.data[0]; 
          let roundResults=gameData.roundResults; 
          if(roundResults[current_round-1].resCount.against>0) 
          { 
            roundResults[current_round-1].success=false; 
          } 
          else roundResults[current_round-1].success=true; 
          db.collection('game').doc(gameData._id).update({   
            data: {   
              roundResults:roundResults 
            }   
          });   
           
          console.log('success'); 
        } else { 
          throw new Error('未找到对应的游戏数据'); 
        } 
      }); 
  } 









  });

  
  